package com.abou.mvc.format.impl;

import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.support.RequestContext;
import com.abou.mvc.format.ITypeFormatter;
import com.abou.utils.common.BeanUtils;

/**
 * The abstract class of all the classes providing format features for a
 * specific type.
 * 
 * @author ztrt8431
 * @param <T> The type of the objects formatted by the class
 */
public abstract class ATypeFormatterImpl<T> implements ITypeFormatter {
  
  /**
   * The parameterized <T> type handled by the DAO.
   */
  private Class<?> tType = null;
  
  /**
   * The constructor of the class
   */
  public ATypeFormatterImpl() {

    super();
    tType = BeanUtils.getParameterizedTypeFromSuperClass(getClass(), 0);
  }
  
  /**
   * @see com.abou.mvc.format.ITypeFormatter#supports(java.lang.Object)
   */
  public boolean supports(Object value) {

    return value != null && tType.isAssignableFrom(value.getClass());
  }
  
  /**
   * @see com.abou.mvc.format.ITypeFormatter#isEmpty(java.lang.Object)
   */
  public boolean isEmpty(Object value) {

    return value == null;
  }
  
  /**
   * Formats the passed value according to the passed locale and context.
   * 
   * @param value The value to format
   * @param locale The locale
   * @param request The servlet request
   * @param requestContext The request context
   * @param textOnly Whether the formatter string should be only a simple text
   *          (no HTML or image).
   * @return The string representation of the passed value
   */
  protected abstract String formatForType(T value, Locale locale,
      HttpServletRequest request, RequestContext requestContext,
      boolean textOnly);
  
  /**
   * @see com.abou.mvc.format.ITypeFormatter#format(java.lang.Object,
   *      java.util.Locale, javax.servlet.http.HttpServletRequest,
   *      org.springframework.web.servlet.support.RequestContext, boolean)
   */
  @SuppressWarnings("unchecked")
  public String format(Object value, Locale locale, HttpServletRequest request,
      RequestContext requestContext, boolean textOnly) {

    String text = null;
    
    if (supports(value)) {
      
      text =
          formatForType((T) value, locale, request, requestContext, textOnly);
    }
    
    return text;
  }
  
}
